// detail.ts - 通用任务详情页
interface TaskData {
  id: string
  type: string
  typeIcon: string
  typeName: string
  startLocation: string
  startAddress?: string
  endLocation: string
  endAddress?: string
  status: string
  statusText: string
  urgencyLevel: string
  urgencyText: string
  passengerCount: number
  createTime: string
  completedTime?: string
  contactPhone: string
  remarks?: string
  canCancel?: boolean
}

interface TimelineItem {
  id: string
  title: string
  time?: string
  completed: boolean
  active: boolean
}

Page({
  data: {
    // 基础信息
    taskId: '',
    currentRole: 'user' as 'user' | 'medical' | 'driver',
    
    // 状态栏高度
    statusBarHeight: '44px',
    
    // 角色信息
    roleInfo: {
      icon: '👤',
      name: '用户端'
    },
    
    // 任务数据
    taskData: null as TaskData | null,
    statusDescription: '',
    
    // 时间轴（用户端）
    timeline: [] as TimelineItem[],
    
    // 患者信息（医护端）
    patientInfo: null as any,
    
    // 运输信息（司机端）
    transportInfo: {
      distance: 0,
      duration: 0
    },
    
    // 路线信息
    routeInfo: {
      startTime: '',
      endTime: ''
    },
    progressPercent: 30,
    
    // 地图相关
    showMap: false,
    currentLocation: null as any,
    mapMarkers: [] as any[],
    polyline: [] as any[],
    eta: 0,
    lastUpdateTime: '',
    
    // 联系信息
    contactInfo: null as any,
    
    // 操作记录
    operations: [] as any[],
    
    // 备注
    remarks: '',
    
    // 状态
    refreshing: false
  },

  /**
   * 页面加载
   */
  onLoad(options: any) {
    // 设置状态栏高度
    this.setStatusBarHeight()
    
    // 检查登录状态
    this.checkLoginStatus()
    
    const { id, role } = options
    if (id) {
      const userRole = role || wx.getStorageSync('userRole') || 'user'
      this.setData({
        taskId: id,
        currentRole: userRole,
        roleInfo: this.getRoleInfo(userRole)
      })
      this.loadTaskDetail()
    }
  },

  /**
   * 设置状态栏高度
   */
  setStatusBarHeight() {
    const systemInfo = wx.getSystemInfoSync()
    const statusBarHeight = systemInfo.statusBarHeight || 44
    
    this.setData({
      statusBarHeight: statusBarHeight + 'px'
    })
  },

  /**
   * 获取角色信息
   */
  getRoleInfo(role: string): { icon: string, name: string } {
    const roleInfoMap: Record<string, { icon: string, name: string }> = {
      'user': { icon: '👤', name: '用户端' },
      'medical': { icon: '🏥', name: '医护端' },
      'driver': { icon: '🚗', name: '司机端' }
    }
    return roleInfoMap[role] || { icon: '👤', name: '用户端' }
  },

  /**
   * 返回上一页
   */
  goBack() {
    wx.navigateBack()
  },

  /**
   * 检查登录状态
   */
  checkLoginStatus() {
    try {
      const userRole = wx.getStorageSync('userRole')
      const userInfo = wx.getStorageSync('userInfo')
      
      if (!userRole || !userInfo) {
        wx.reLaunch({
          url: '/pages/login/login'
        })
        return
      }
    } catch (e) {
      console.log('检查登录状态失败:', e)
      wx.reLaunch({
        url: '/pages/login/login'
      })
    }
  },

  /**
   * 页面显示时
   */
  onShow() {
    this.loadTaskDetail()
  },

  /**
   * 下拉刷新
   */
  onPullDownRefresh() {
    this.loadTaskDetail()
    setTimeout(() => {
      wx.stopPullDownRefresh()
    }, 1500)
  },

  /**
   * 加载任务详情
   */
  loadTaskDetail() {
    wx.showLoading({
      title: '加载中...'
    })

    // 模拟API调用
    setTimeout(() => {
      const mockData = this.generateMockTaskData()
      
      this.setData({
        taskData: mockData.taskData,
        statusDescription: mockData.statusDescription,
        timeline: mockData.timeline,
        patientInfo: mockData.patientInfo,
        transportInfo: mockData.transportInfo,
        routeInfo: mockData.routeInfo,
        currentLocation: mockData.currentLocation,
        contactInfo: mockData.contactInfo,
        operations: mockData.operations,
        showMap: mockData.showMap,
        eta: mockData.eta,
        lastUpdateTime: mockData.lastUpdateTime
      })
      
      this.updateMapMarkers()
      wx.hideLoading()
    }, 1000)
  },

  /**
   * 生成模拟任务数据
   */
  generateMockTaskData() {
    const role = this.data.currentRole
    const taskId = this.data.taskId

    const baseTaskData: TaskData = {
      id: taskId,
      type: 'ambulance',
      typeIcon: '🚑',
      typeName: '救护车',
      startLocation: '辽宁省-沈阳市',
      startAddress: '某某东大街112号院东恒生宇楼B座11.5',
      endLocation: '北京市-东城区',
      endAddress: '协和医院本部',
      status: 'in_progress',
      statusText: '已发车',
      urgencyLevel: 'low',
      urgencyText: '低',
      passengerCount: 2,
      createTime: '2025-09-07 周日 09:22',
      contactPhone: '135 0000 0000',
      remarks: '患者意识清醒，疑似心脏病发作',
      canCancel: false
    }

    // 根据角色调整状态文本
    if (role === 'medical') {
      baseTaskData.statusText = '救援中'
    } else if (role === 'driver') {
      baseTaskData.statusText = '运输中'
    }

    const statusDescriptions: Record<string, string> = {
      'user': '救援人员正在前往现场，请保持电话畅通，确保患者状态稳定',
      'medical': '请根据患者情况准备相应的医疗设备，注意患者生命体征',
      'driver': '请按照导航路线行驶，注意行车安全，保持与医护人员联系'
    }

    // 时间轴数据（用户端）
    const timeline: TimelineItem[] = [
      { id: '1', title: '申请已提交', time: '14:30', completed: true, active: false },
      { id: '2', title: '系统匹配资源', time: '14:32', completed: true, active: false },
      { id: '3', title: '救援人员确认', time: '14:35', completed: true, active: false },
      { id: '4', title: '救援人员出发', time: '14:40', completed: true, active: false },
      { id: '5', title: '正在前往现场', time: '', completed: false, active: true },
      { id: '6', title: '到达现场救援', time: '', completed: false, active: false },
      { id: '7', title: '救援完成', time: '', completed: false, active: false }
    ]

    // 患者信息（医护端）
    const patientInfo = {
      condition: '123',
      notes: '患者有糖尿病病史，正在服用降糖药物'
    }

    // 运输信息（司机端）
    const transportInfo = {
      distance: 12.5,
      duration: 25
    }

    // 路线信息
    const routeInfo = {
      startTime: '14:40',
      endTime: '15:05'
    }

    // 实时位置
    const currentLocation = {
      latitude: 39.908823,
      longitude: 116.397470
    }

    // 联系信息
    const contactInfoMap: Record<string, any> = {
      'user': {
        name: '张医生',
        role: '主治医师',
        workId: 'BJ001',
        avatar: '../../images/doctor-avatar.jpg',
        phone: '400-123-4567'
      },
      'medical': {
        name: '王先生',
        role: '申请人',
        workId: '',
        avatar: '../../images/user-avatar.jpg',
        phone: '138****8000'
      },
      'driver': {
        name: '李护士',
        role: '随车护士',
        workId: 'BJ002',
        avatar: '../../images/nurse-avatar.jpg',
        phone: '400-123-4567'
      }
    }

    // 操作记录
    const operations = [
      { 
        id: '1', 
        time: '14:35', 
        user: '张医生', 
        role: '主治医师',
        action: '接受了救援任务',
        actionIcon: '✅',
        timeAgo: '25分钟前',
        details: '已确认具备相应救治资质，立即响应救援请求'
      },
      { 
        id: '2', 
        time: '14:38', 
        user: '李师傅', 
        role: '救护车司机',
        action: '确认运输任务',
        actionIcon: '🚗',
        timeAgo: '22分钟前',
        details: '车辆检查完毕，燃油充足，已出发前往指定地点'
      },
      { 
        id: '3', 
        time: '14:40', 
        user: '张医生', 
        role: '主治医师',
        action: '开始前往现场',
        actionIcon: '🏃‍♂️',
        timeAgo: '20分钟前',
        details: '携带应急医疗设备，预计5分钟内到达现场'
      },
      { 
        id: '4', 
        time: '14:45', 
        user: '李师傅', 
        role: '救护车司机',
        action: '更新了车辆位置',
        actionIcon: '📍',
        timeAgo: '15分钟前',
        details: '当前位置：建国门内大街，距离目标地点约2公里'
      },
      { 
        id: '5', 
        time: '14:50', 
        user: '王护士', 
        role: '随车护士',
        action: '准备医疗设备',
        actionIcon: '🏥',
        timeAgo: '10分钟前',
        details: '心电监护仪、除颤器、氧气罐等设备检查完毕'
      },
      { 
        id: '6', 
        time: '14:55', 
        user: '系统', 
        role: '调度中心',
        action: '通知患者家属',
        actionIcon: '📞',
        timeAgo: '5分钟前',
        details: '已成功联系患者紧急联系人，告知救援进展情况'
      }
    ]

    return {
      taskData: baseTaskData,
      statusDescription: statusDescriptions[role],
      timeline: timeline,
      patientInfo: patientInfo,
      transportInfo: transportInfo,
      routeInfo: routeInfo,
      currentLocation: currentLocation,
      contactInfo: contactInfoMap[role],
      operations: operations,
      showMap: baseTaskData.status === 'in_progress',
      eta: 15,
      lastUpdateTime: '15:02'
    }
  },

  /**
   * 更新地图标记
   */
  updateMapMarkers() {
    const currentLocation = this.data.currentLocation
    if (!currentLocation) return

    const markers = [
      {
        id: 1,
        latitude: currentLocation.latitude,
        longitude: currentLocation.longitude,
        iconPath: '../../images/ambulance-marker.png',
        width: 40,
        height: 40,
        title: '救援车辆当前位置'
      }
    ]

    this.setData({
      mapMarkers: markers
    })
  },

  /**
   * 拨打电话
   */
  makePhoneCall(e: any) {
    const phone = e.currentTarget.dataset.phone
    wx.makePhoneCall({
      phoneNumber: phone,
      fail: () => {
        wx.showToast({
          title: '拨号失败',
          icon: 'none'
        })
      }
    })
  },

  /**
   * 联系客服
   */
  contactService() {
    wx.showModal({
      title: '客服电话',
      content: '24小时客服热线：400-123-4567\n任务ID：' + this.data.taskId,
      confirmText: '拨打电话',
      success: (res) => {
        if (res.confirm) {
          wx.makePhoneCall({
            phoneNumber: '400-123-4567'
          })
        }
      }
    })
  },

  /**
   * 刷新状态
   */
  refreshStatus() {
    this.setData({ refreshing: true })
    
    setTimeout(() => {
      this.loadTaskDetail()
      this.setData({ refreshing: false })
      
      wx.showToast({
        title: '状态已更新',
        icon: 'success'
      })
    }, 1500)
  },

  /**
   * 取消任务（用户端）
   */
  cancelTask() {
    wx.showModal({
      title: '确认取消',
      content: '确定要取消这个救援申请吗？取消后可能产生一定费用。',
      success: (res) => {
        if (res.confirm) {
          wx.showToast({
            title: '申请已取消',
            icon: 'success'
          })
          
          setTimeout(() => {
            wx.navigateBack()
          }, 1500)
        }
      }
    })
  },

  /**
   * 拒绝任务（医护端）
   */
  rejectTask() {
    wx.showModal({
      title: '拒绝任务',
      content: '确定拒绝这个救援任务吗？',
      success: (res) => {
        if (res.confirm) {
          wx.showToast({
            title: '任务已拒绝',
            icon: 'none'
          })
          
          setTimeout(() => {
            wx.navigateBack()
          }, 1500)
        }
      }
    })
  },

  /**
   * 接受任务（医护端）
   */
  acceptTask() {
    wx.showModal({
      title: '接受任务',
      content: '确认接受这个救援任务吗？',
      success: (res) => {
        if (res.confirm) {
          wx.showToast({
            title: '任务已接受',
            icon: 'success'
          })
          this.loadTaskDetail()
        }
      }
    })
  },

  /**
   * 开始救援（医护端）
   */
  startRescue() {
    wx.showToast({
      title: '开始救援',
      icon: 'success'
    })
    this.loadTaskDetail()
  },

  /**
   * 完成救援（医护端）
   */
  completeRescue() {
    wx.showModal({
      title: '完成救援',
      content: '确认救援任务已完成？',
      success: (res) => {
        if (res.confirm) {
          wx.showToast({
            title: '救援已完成',
            icon: 'success'
          })
          this.loadTaskDetail()
        }
      }
    })
  },

  /**
   * 打开导航（司机端）
   */
  openNavigation() {
    const taskData = this.data.taskData
    if (!taskData) return

    wx.openLocation({
      latitude: 39.916423,
      longitude: 116.397079,
      name: taskData.endLocation,
      address: taskData.endLocation,
      scale: 18
    })
  },

  /**
   * 更新位置（司机端）
   */
  updateCurrentLocation() {
    wx.getLocation({
      type: 'gcj02',
      success: (res) => {
        this.setData({
          currentLocation: {
            latitude: res.latitude,
            longitude: res.longitude
          },
          lastUpdateTime: new Date().toLocaleTimeString()
        })
        
        this.updateMapMarkers()
        
        wx.showToast({
          title: '位置已更新',
          icon: 'success'
        })
      },
      fail: () => {
        wx.showToast({
          title: '获取位置失败',
          icon: 'none'
        })
      }
    })
  },

  /**
   * 到达目的地（司机端）
   */
  arriveDestination() {
    wx.showModal({
      title: '确认到达',
      content: '确认已到达目的地？',
      success: (res) => {
        if (res.confirm) {
          wx.showToast({
            title: '已到达目的地',
            icon: 'success'
          })
          this.loadTaskDetail()
        }
      }
    })
  },

  /**
   * 显示更多操作记录
   */
  showMoreOperations() {
    wx.showModal({
      title: '操作记录',
      content: '完整的操作记录功能正在开发中，敬请期待！',
      showCancel: false,
      confirmText: '知道了'
    })
  },

  /**
   * 上传图片
   */
  uploadImage() {
    wx.chooseImage({
      count: 9,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: () => {
        wx.showLoading({
          title: '上传中...'
        })
        // 这里应该实现实际的上传逻辑
        setTimeout(() => {
          wx.hideLoading()
          wx.showToast({
            title: '上传成功',
            icon: 'success'
          })
        }, 1500)
      }
    })
  },

  /**
   * 上传视频
   */
  uploadVideo() {
    wx.chooseVideo({
      sourceType: ['album', 'camera'],
      maxDuration: 60,
      camera: 'back',
      success: () => {
        wx.showLoading({
          title: '上传中...'
        })
        // 这里应该实现实际的上传逻辑
        setTimeout(() => {
          wx.hideLoading()
          wx.showToast({
            title: '上传成功',
            icon: 'success'
          })
        }, 1500)
      }
    })
  },

  /**
   * 备注输入失焦
   */
  onRemarksBlur(e: any) {
    const value = e.detail.value
    this.setData({
      remarks: value
    })
  },

  /**
   * 确认到达
   */
  confirmArrival() {
    wx.showModal({
      title: '确认到达',
      content: '确认已到达目的地？',
      success: (res) => {
        if (res.confirm) {
          wx.showToast({
            title: '已确认到达',
            icon: 'success'
          })
          
          setTimeout(() => {
            wx.navigateBack()
          }, 1500)
        }
      }
    })
  },

  /**
   * 显示更多选项
   */
  showMore() {
    wx.showActionSheet({
      itemList: ['联系客服', '导出详情', '分享任务'],
      success: (res) => {
        switch(res.tapIndex) {
          case 0:
            this.contactService()
            break
          case 1:
            wx.showToast({
              title: '功能开发中',
              icon: 'none'
            })
            break
          case 2:
            wx.showShareMenu({
              withShareTicket: true
            })
            break
        }
      }
    })
  },

  /**
   * 页面分享
   */
  onShareAppMessage() {
    return {
      title: '立体救援 - 任务详情',
      path: `/pages/detail/detail?id=${this.data.taskId}&role=${this.data.currentRole}`
    }
  }
})
